package com.google.code.tretris.rendering;

import javax.microedition.khronos.opengles.GL10;

import com.google.code.tretris.common.Tetromino;
import com.google.code.tretris.common.WKC;
import com.google.code.tretris.events.UpdateBoardEvent;

public class Grid extends MVComplexObject {

	private int[] board;

	private static final float X_START = 0f;
	private static final float Y_START = 0f;
	
	private static final float[] DARK = {
		0.4f, 0.4f, 0.4f, 0.1f
	};
	
	private Shape shape;
	private String userId;
	private Cube[][] cubes;	

	private Grid(final String userId, final Shape shape, final Cube[][] cubes) {
		this.userId = userId;
		this.shape = shape;
		this.cubes = cubes;
		this.x = X_START;
		this.y = Y_START;
	}

	public void draw(GL10 gl) {
		drawGrid(gl);
		//shape.draw(gl);
	}

	private void drawGrid(GL10 gl) {
		if (board != null) {			
			for (int row = 0; row < WKC.BOARD_HEIGHT; row++) {
				for(int col = 0; col < WKC.BOARD_WIDTH; col++) {
					gl.glPushMatrix();
					Cube currentCube = this.cubes[row][col];
//					currentCube.setX(this.x, col);
//					currentCube.setY(this.y, WKC.BOARD_HEIGHT - row);
					currentCube.setPosition(x * col, y * row, 0);
					int index = col+row*WKC.BOARD_WIDTH;
					if (board[index] != 0) {
						float[] color = Tetromino.COLORS.get(board[index]);
						currentCube.setColor(color[0], color[1], color[2]);	
					} else {
						currentCube.setColor(DARK[0], DARK[1], DARK[2]);
					}
					currentCube.renderShape(gl);
					gl.glPopMatrix();
				}
			}
		}
	}
	
	public void update(final UpdateBoardEvent e) {
		if (userId.equals(e.getClientID())) {			
			this.board = e.getBlocks();
			shape.update(e);
		}
	}

		
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((userId == null) ? 0 : userId.hashCode());
		return result;
	}


	/**
	 * A grid is considered equal if the userId is the same
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Grid other = (Grid) obj;
		if (userId == null) {
			if (other.userId != null)
				return false;
		} else if (!userId.equals(other.userId))
			return false;
		return true;
	}
	
	/**
	 * Builds a grid
	 * @author mike
	 *
	 */
	public static final class Builder {
		private String clientId;
		public Builder clientId(String clientId) {
			this.clientId = clientId;
			return this;
		}
		
		private Shape shape;
		public Builder shape(Shape shape) {
			this.shape = shape;
			return this;
		}
		
		
		public Grid build() {
			Cube[][] cubes = new Cube[WKC.BOARD_HEIGHT][WKC.BOARD_WIDTH];
			for (int row = 0; row < WKC.BOARD_HEIGHT; row++){
				for (int col = 0; col < WKC.BOARD_WIDTH; col++) {
					cubes[row][col] = new Cube(1f);
				}
			}			
			return new Grid(clientId, shape, cubes);
		}
	}

}
